#include <header.h>

/* Usage:  */
int main(int argc, char *argv[]){                                  

    char *Port="8080";//监听端口
    char *IP="0.0.0.0";//本机IP

    //创建套接字
    int socketFD=socket(AF_INET,SOCK_STREAM,0);

    //绑定套接字到端口和IP
    // int PortNet=htons(atoi(Port));//将端口字符串转化为数字，在转化为网络字节序
    // struct in_addr IPNet;//ipv4地址结构体，用于接收主机字节序的IP地址
    // inet_aton(IP,&IPNet);//转化为主机字节序

    struct sockaddr_in socketAddr;
    socketAddr.sin_family=AF_INET;//TCP
    socketAddr.sin_addr.s_addr=inet_addr(IP);//IP
    socketAddr.sin_port=htons(atoi(Port));
    int res_bind =bind(socketFD,(struct sockaddr*)&socketAddr,sizeof(socketAddr));//绑定到套接字
    ERROR_CHECK(res_bind,-1,"bind");                                                                                  

    //监听端口
    listen(socketFD,10);

    //accept获取链接
    int connectFD1=accept(socketFD,NULL,NULL);
    int connectFD2=accept(socketFD,NULL,NULL);

    fd_set selectFD;
    while(1){
        FD_ZERO(&selectFD);
        FD_SET(connectFD1,&selectFD);
        FD_SET(connectFD2,&selectFD);
        select(connectFD2+1,&selectFD,NULL,NULL,NULL);
        if(FD_ISSET(connectFD1,&selectFD))
        {
            char buf[100]={0};
            int res_recv=recv(connectFD1,buf,sizeof(buf),0);
            ERROR_CHECK(res_recv,-1,"recv");
            // if(res_recv==0){
            //     printf("%d断开连接\n",connectFD1);
            //     FD_CLR(connectFD1,&selectFD);
            //     if(selectFD==0)
            //     break;
            // }
            printf("get your massage:%s\n",buf);
            int res_send=send(connectFD2,buf,sizeof(buf),0);
            ERROR_CHECK(res_send,-1,"send");
        }
        if(FD_ISSET(connectFD2,&selectFD))
        {
            char buf[100]={0};
            int res_recv=recv(connectFD2,buf,sizeof(buf),0);
            ERROR_CHECK(res_recv,-1,"recv");
            // if(res_recv==0){
            //     printf("%d断开连接\n",connectFD1);
            //     FD_CLR(connectFD1,&selectFD);
            //     if(selectFD==0)
            //     break;
            // }
            printf("get your massage:%s\n",buf);
            int res_send=send(connectFD1,buf,sizeof(buf),0);
            ERROR_CHECK(res_send,-1,"send");
        }

    }
    close(socketFD);


    return 0;

}

